import os
from ctypes import *

from flask import Flask, render_template, request

app = Flask(__name__)
basepath = os.path.dirname(__file__)
inpath = bytes(basepath + "\\files\\putin.txt", "gbk")
outpath = bytes(basepath + "\\files\\out.txt", "gbk")
display=[]
result=[]

@app.route('/',methods=['POST','GET'])
def calculate():
    if request.method=='POST':
        content=request.form.get("eval")
        operate=request.form.get('type')
        if operate=='add':
            fileinput = open(basepath + "\\files\\putin.txt", 'w')
            fileinput.write(content)
            fileinput.write('\n')
            tmplen=len(content)
            pos=0
            while pos<tmplen:
                display.append(content[pos:pos+19:1])
                pos=pos+19
            return render_template('index.html',display=display,result=result)
        if operate=='eq':
            dll = cdll.LoadLibrary(basepath+"\\calculator.dll")
            dll.calcpar(inpath, outpath)
            with open(basepath+"\\files\\out.txt", 'r+') as file:
                for line in file:
                    tmplenr=len(line)
                    pos=0
                    while pos<tmplenr:
                        result.append(line[pos:pos+19:1])
                        pos=pos+19
            return render_template('index.html',display=display,result=result)
        if operate=='cls':
            display.clear()
            result.clear()
            fileinput = open(basepath + "\\files\\putin.txt", 'w')
            fileinput.write('\n')
            fileout=open(basepath+"\\files\\out.txt",'w')
            fileout.write('\n')
            return render_template('index.html',display=display,result=result)
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)
